from email.mime.text import MIMEText
import smtplib
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
from common.read_config import*
import os
import datetime

reportPath = os.path.split(os.path.realpath(__file__))[0] + r"\report"
# os.path.split(os.path.realpath(__file__))[0]  获取工程的文件目录


class SendEmail:
    def get_report(self):  # 该函数作用是为了在测试报告的路径下找到最新的测试报告
        dirs = os.listdir(reportPath)  # 返回文件下的文件名、文件夹的列表
        dirs.sort()
        newreportname = dirs[-1]
        return newreportname

    def take_message(self):  # 该函数目的是为了准备发送邮件的消息内容
        print("报告读取中------------------------------------------")
        newreport = self.get_report()
        self.msg = MIMEMultipart()  # 创建一个附件实例
        self.msg['Subject'] = con.get_config(section="email_config", key="email_title")  # 邮件标题
        date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        with open(os.path.join(reportPath, newreport), 'r', encoding="utf-8") as f:
            mailbody = f.read()
            email_text = MIMEText(date + " " + con.get_config(section="email_config", key="email_text"))  # 邮件的正文
            att1 = MIMEText(mailbody, 'base64', 'utf-8')   # 邮件附件编码
            att1['Content-Type'] = 'application/octet-stream'
            att1.add_header('Content-Disposition', 'attachment', filename=('gbk', '', '%s' % newreport))  # 添加邮件header
            self.msg.attach(att1)  # 将html文件作为附件添加到邮件当中
            self.msg.attach(email_text)  # 将email_text添加到正文内容
        print("-----------------------------------------报告读取完毕")

    def send(self):
        if con.get_config(section="email_config", key="take_on") is True:
            print("邮件准备发送-----------------------------------------")
            my_email = con.get_config(section="email_config", key="my_email")   # QQ账号
            my_pass = con.get_config(section="email_config", key="my_pass")  # QQ授权码
            send_email = con.get_config(section="email_config", key="send_email").split(",")  #
            self.take_message()

            # 将邮箱名称以化名进行显示 方便知道邮件来源
            self.msg['from'] = formataddr([con.get_config(section="email_config", key="email_origin"), my_email])
            # self.msg['to'] = formataddr(['', send_email])  # 单个人发邮件
            self.msg['to'] = ','.join(send_email)  # 群发发邮件
            smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)   # QQ邮箱服务以及端口
            smtp.ehlo()
            smtp.login(my_email, my_pass)  # 进行登录QQ邮箱
            smtp.sendmail(my_email, send_email, self.msg.as_string())
            # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件操作
            # 由于sendemail要传String类型，所以要用.as_string()把内容组合成字符串
            smtp.quit()   # 关闭连接
            print("-----------------------------------------邮件发送完成")
        else:
            exit()


# if __name__ == '__main__':
#     if con.get_config(section="email_config", key="take_on") is True:
#         SendEmail().send()
#     else:
#         exit()
